package com.wing.cabinet.controller.app;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.cabinet.model.entity.CabinetCargoSpace;
import com.wing.cabinet.model.entity.CellInventoryOutAmount;
import com.wing.cabinet.model.request.CellInventorySpaceForm;
import com.wing.cabinet.model.request.UseInventoryInoutDetailForm;
import com.wing.cabinet.model.response.*;
import com.wing.cabinet.service.CellInventoryOutAmountService;
import com.wing.cabinet.service.CellInventorySpaceService;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.setting.model.entity.SystemRuleInfo;
import com.wing.setting.service.SystemRuleInfoService;
import com.wing.web.utils.JwtUtils;
import com.wing.web.utils.LocaleMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author
 */
@Validated
@Api(value = "App-售刀柜货道产品管理", tags = "售刀柜货道产品管理")
@RestController("appCellInventorySpaceController")
@RequestMapping("cabinet/app/cellInventorySpace")
@Slf4j
public class CellInventorySpaceController {

    @Autowired
    private CellInventorySpaceService cellInventorySpaceService;
    @Autowired
    private LocaleMessage localeMessage;

    @Autowired
    private SystemRuleInfoService systemRuleInfoService;

    @Autowired
    private CellInventoryOutAmountService cellInventoryOutAmountService;


    @ApiOperation(value = "领用刀具列表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "name", value = "名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<CellInventorySpaceVO> list(
            @RequestParam(name = "page",defaultValue = "1") Integer page
            ,@RequestParam(name = "limit",defaultValue = "10") Integer limit
            ,@RequestParam(name = "sort",defaultValue = "id") String sort
            ,@RequestParam(name = "order",defaultValue = "asc") String order
            ,Long productCategoryId
            ,Long productTypeId
            ,String cabCodes
            ,String skuName
            ,String brandName
            ,String typeName
            ,String name
            ,Long workOrderId
            ,Long processId
    ) {
        Page<CellInventorySpaceVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        params.put("productCategoryId",productCategoryId);
        params.put("productTypeId",productTypeId);
        if (StringUtils.isNotBlank(cabCodes)){
            String [] cabCodeArray=cabCodes.split(",");
            params.put("cabCodes",cabCodeArray);
        }
        params.put("skuName",skuName);
        params.put("brandName",brandName);
        params.put("typeName",typeName);
        params.put("name",name);
        params.put("workOrderId",workOrderId);
        params.put("processId",processId);
        Page<CellInventorySpaceVO> list = new Page<>();
        if (workOrderId!=null&&workOrderId!=0){
            pg.setSize(Integer.MAX_VALUE);
//            params.put("queryFlag","main");
//            list=cellInventorySpaceService.pageList4app(pg, params);
//            params.put("queryFlag","spare");
            params.put("queryFlag","simple");
            list=cellInventorySpaceService.pageList4app(pg, params);

            if (list.getRecords().size()==0){
                params.put("queryFlag",null);
                params.put("workOrderId",null);
                list=cellInventorySpaceService.pageList4app(pg, params);
            }
        }else{
            list=cellInventorySpaceService.pageList4app(pg, params);

        }

        PageResult pageResult=new PageResult<>(list.getRecords(), list.getTotal());
//        List<SystemRuleInfo> systemRuleInfos=systemRuleInfoService.list();
        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getRuleInfo();
        if (systemRuleInfo!=null){
            Boolean showPriceFlag=systemRuleInfo.getShowPriceFlag();
            pageResult.setTotalFlag(systemRuleInfo.getTotalFlag());
            if(systemRuleInfo.getTotalFlag()&&systemRuleInfo.getTotal()!=null&&systemRuleInfo.getTotal().doubleValue()>0){
                List<CellInventoryOutAmount> cellInventoryOutAmounts=cellInventoryOutAmountService.list(new QueryWrapper<CellInventoryOutAmount>().eq("creator", JwtUtils.getLoginUserId()));
                if (cellInventoryOutAmounts.size()>0){
                    pageResult.setCurrentTotal(cellInventoryOutAmounts.get(0).getTotal());
                }else{
                    pageResult.setCurrentTotal(BigDecimal.valueOf(0));
                }
                pageResult.setSettingTotal(systemRuleInfo.getTotal());
            }
            list.getRecords().forEach(item->{
                item.setShowPriceFlag(showPriceFlag);
            });
        }

        return pageResult;
    }

    @ApiOperation(value = "查询货道上产品库存(领用列表)", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "productCategoryId", value = "产品分类id", defaultValue = "", example = "", dataType = "Long", paramType = "query")
            ,@ApiImplicitParam(name = "productTypeId", value = "产品类型id", defaultValue = "", example = "", dataType = "Long", paramType = "query")
            ,@ApiImplicitParam(name = "skuName", value = "SKU名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "brandName", value = "品牌名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "typeName", value = "产品类型名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "cabCodes", value = "柜子编号", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    @GetMapping("/listSku")
    public PageResult<CellInventorySpaceVO> listSku(
            @RequestParam(name = "page",  defaultValue = "1", required = false) Integer page
            ,@RequestParam(name = "limit",  defaultValue = "10", required = false) Integer limit
            ,@RequestParam(name = "sort",  defaultValue = "create_time", required = false) String sort
            ,@RequestParam(name = "order",  defaultValue = "asc", required = false) String order
            ,Long productCategoryId
            ,Long productTypeId
            ,String cabCodes
            ,String skuName
            ,String brandName
            ,String typeName
            ,String name
            ,Long workOrderId
            ,Long processId
    ) {
        Page<CellSingleInventoryProductVO> pg = new Page<>(page, Integer.MAX_VALUE);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        params.put("productCategoryId",productCategoryId);
        params.put("productTypeId",productTypeId);
        if (StringUtils.isNotBlank(cabCodes)){
            String [] cabCodeArray=cabCodes.split(",");
            params.put("cabCodes",cabCodeArray);
        }
        params.put("skuName",skuName);
        params.put("brandName",brandName);
        params.put("typeName",typeName);
        params.put("name",name);
        params.put("workOrderId",workOrderId);
        params.put("processId",processId);
        params.put("queryFlag","simple");
        Page<CellInventorySpaceVO> list = cellInventorySpaceService.pageListSKU4app(pg, params);
        if (list.getRecords().size()==0){
            params.put("workOrderId",null);
            list = cellInventorySpaceService.pageListSKU4app(pg, params);
        }
        //int id=1;
        //for (int i=0;i<list.getRecords().size();i++){
        //    list.getRecords().get(i).setId((page-1)*limit+Long.valueOf(i+1));
        //}
        PageResult pageResult=new PageResult<>(list.getRecords(), list.getTotal());
//        List<SystemRuleInfo> systemRuleInfos=systemRuleInfoService.list();
        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getRuleInfo();
        if (systemRuleInfo!=null){
            Boolean showPriceFlag=systemRuleInfo.getShowPriceFlag();
            pageResult.setTotalFlag(systemRuleInfo.getTotalFlag());
            if(systemRuleInfo.getTotalFlag()&&systemRuleInfo.getTotal()!=null&&systemRuleInfo.getTotal().doubleValue()>0){
                List<CellInventoryOutAmount> cellInventoryOutAmounts=cellInventoryOutAmountService.list(new QueryWrapper<CellInventoryOutAmount>().eq("creator", JwtUtils.getLoginUserId()));
                if (cellInventoryOutAmounts.size()>0){
                    pageResult.setCurrentTotal(cellInventoryOutAmounts.get(0).getTotal());
                }else{
                    pageResult.setCurrentTotal(BigDecimal.valueOf(0));
                }
                pageResult.setSettingTotal(systemRuleInfo.getTotal());
            }
            list.getRecords().forEach(item->{
                item.setShowPriceFlag(showPriceFlag);
            });
        }
        return pageResult;
    }


    @PostMapping("/recycle/getSpaces")
    public JsonResult<List<CellInventorySpaceVO>> getSpaces(@RequestBody UseInventoryInoutDetailForm useInventoryInoutDetailForm){
        if (useInventoryInoutDetailForm.getQuantity()==null){
            useInventoryInoutDetailForm.setQuantity(1);
        }
        if (useInventoryInoutDetailForm.getStorageType()==null){
            useInventoryInoutDetailForm.setStorageType(CabinetCargoSpace.SpaceNature.common);
        }
        return cellInventorySpaceService.getSpaces(useInventoryInoutDetailForm);
    }

    @PostMapping("/getSpaces")
    public JsonResult<List<CellInventorySpaceVO>> getSpacesNewOld(@RequestBody UseInventoryInoutDetailForm useInventoryInoutDetailForm){
        log.info("getSpaces4NewOld:{}",JSON.toJSONString(useInventoryInoutDetailForm));
        if (useInventoryInoutDetailForm.getQuantity()==null){
            useInventoryInoutDetailForm.setQuantity(1);
        }
        if (useInventoryInoutDetailForm.getStorageType()==null){
            useInventoryInoutDetailForm.setStorageType(CabinetCargoSpace.SpaceNature.common);
        }
        return cellInventorySpaceService.getSpaces(useInventoryInoutDetailForm);
    }

    @PostMapping("/getSpaces4MoreKnife")
    public JsonResult<OldNewSpaceVO> getSpaces4MoreKnife(@RequestBody UseInventoryInoutDetailForm useInventoryInoutDetailForm){
        if (useInventoryInoutDetailForm.getQuantity()==null){
            useInventoryInoutDetailForm.setQuantity(1);
        }
        if (useInventoryInoutDetailForm.getStorageType()==null){
            useInventoryInoutDetailForm.setStorageType(CabinetCargoSpace.SpaceNature.common);
        }
        return cellInventorySpaceService.getSpaces4MoreKnife(useInventoryInoutDetailForm);
    }

    @PostMapping("/getOptimalSpacesV1")
    public JsonResult<List<UseInventoryInoutDetailForm>> getOptimalSpacesV1(@RequestBody UseInventoryInoutDetailForm useInventoryInoutDetailForm){
        try{
            return JsonResult.success(cellInventorySpaceService.getOptimalSpaces(useInventoryInoutDetailForm));
        }catch (Exception e){
            log.error("get optimal space fail",e);
            return JsonResult.fail(e.getMessage(),new ArrayList<>());
        }
    }

    @PostMapping("/getOptimalSpaces")
    public JsonResult<List<CabOptimalSpaces>> getOptimalSpaces(@RequestBody UseInventoryInoutDetailForm useInventoryInoutDetailForm){
        try{
            return JsonResult.success(cellInventorySpaceService.getCabOptimalSpaces(useInventoryInoutDetailForm));
        }catch (Exception e){
            log.error("get optimal space fail",e);
            return JsonResult.fail(e.getMessage(),new ArrayList<>());
        }
    }

    @PostMapping("/getOptimalLanesSpaces")
    public JsonResult<SpacesResultVO> getOptimalLanesSpaces(@RequestBody UseInventoryInoutDetailForm useInventoryInoutDetailForm){
        try{
            log.info("getOptimalLanesSpaces param:{}", JSON.toJSONString(useInventoryInoutDetailForm));
            process(useInventoryInoutDetailForm);
            SpacesResultVO spacesResultVO=cellInventorySpaceService.getCabOptimalLanesSpaces(useInventoryInoutDetailForm);
            //兼容android类型
            if(CollectionUtil.isNotEmpty(spacesResultVO.getLaneList())){
                for (CabOptimalSpaces cabOptimalSpace:spacesResultVO.getLaneList()){
                    if (CollectionUtil.isNotEmpty(cabOptimalSpace.getResultLaneList())){
                        for (int i=0;i<cabOptimalSpace.getResultLaneList().size();i++){
                            cabOptimalSpace.getResultLaneList().get(i).setId(Long.valueOf(i));
                        }
                    }
                    if (CollectionUtil.isNotEmpty(cabOptimalSpace.getResultStorageSpaceList())){
                        for (int i=0;i<cabOptimalSpace.getResultStorageSpaceList().size();i++){
                            cabOptimalSpace.getResultStorageSpaceList().get(i).setId(Long.valueOf(i));
                        }
                    }
                }
            }
            if(CollectionUtil.isNotEmpty(spacesResultVO.getSpaceList())){
                for (CabOptimalSpaces cabOptimalSpace:spacesResultVO.getSpaceList()){
                    if (CollectionUtil.isNotEmpty(cabOptimalSpace.getResultLaneList())){
                        for (int i=0;i<cabOptimalSpace.getResultLaneList().size();i++){
                            cabOptimalSpace.getResultLaneList().get(i).setId(Long.valueOf(i));
                        }
                    }
                    if (CollectionUtil.isNotEmpty(cabOptimalSpace.getResultStorageSpaceList())){
                        for (int i=0;i<cabOptimalSpace.getResultStorageSpaceList().size();i++){
                            cabOptimalSpace.getResultStorageSpaceList().get(i).setId(Long.valueOf(i));
                        }
                    }
                }
            }
            log.info("getOptimalLanesSpaces response:{}", JSON.toJSONString(spacesResultVO));
            return JsonResult.success(spacesResultVO);
        }catch (Exception e){
            log.error("get optimal space fail",e);
            return JsonResult.fail(e.getMessage(),new SpacesResultVO());
        }
    }

    void process(UseInventoryInoutDetailForm useInventoryInoutDetailForm){
        UseInventoryInoutDetailForm useInventoryInoutDetailFormResult=new UseInventoryInoutDetailForm();
        BeanUtils.copyProperties(useInventoryInoutDetailForm,useInventoryInoutDetailFormResult);
        Map<String,UseInventoryInoutDetailForm> resultMap=new HashMap<>();
        useInventoryInoutDetailForm.getDetailList().forEach(e->{
            UseInventoryInoutDetailForm temp=resultMap.get(e.getSkuCode());
            if (temp!=null){
                temp.setQuantity(temp.getQuantity()+e.getQuantity());
            }else{
                resultMap.put(e.getSkuCode(),e);
            }
        });
        List<UseInventoryInoutDetailForm> resultDetailList=new ArrayList<>();
        resultMap.forEach((k,v)->{
            resultDetailList.add(v);
        });
        useInventoryInoutDetailForm.setDetailList(resultDetailList);

    }

    @PostMapping("/getUserSpaces")
    public JsonResult<OldNewSpaceVO> getUserSpaces(@RequestBody UseInventoryInoutDetailForm useInventoryInoutDetailForm){
        log.info("getUserSpaces param:{}", JSONObject.toJSONString(useInventoryInoutDetailForm));
        if (useInventoryInoutDetailForm.getQuantity()==null){
            useInventoryInoutDetailForm.setQuantity(1);
        }
        if (useInventoryInoutDetailForm.getStorageType()==null){
            useInventoryInoutDetailForm.setStorageType(CabinetCargoSpace.SpaceNature.personal);
        }
        return cellInventorySpaceService.getUserSpaces(useInventoryInoutDetailForm);
    }

    @PostMapping("/getUserSpaces4MoreKnife")
    public JsonResult<OldNewSpaceVO> getUserSpaces4MoreKnife(@RequestBody UseInventoryInoutDetailForm useInventoryInoutDetailForm){
        if (useInventoryInoutDetailForm.getQuantity()==null){
            useInventoryInoutDetailForm.setQuantity(1);
        }
        if (useInventoryInoutDetailForm.getStorageType()==null){
            useInventoryInoutDetailForm.setStorageType(CabinetCargoSpace.SpaceNature.personal);
        }
        return cellInventorySpaceService.getUserSpaces4MoreKnife(useInventoryInoutDetailForm);
    }

    @ApiOperation(value = "售刀柜货道库存列表(含有产品的)", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "name", value = "名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    @GetMapping("/listCellInventorySpace")
    public PageResult<CellInventorySpaceVO> listWx(
            @RequestParam(name = "page",defaultValue = "1") Integer page
            ,@RequestParam(name = "limit",defaultValue = "10") Integer limit
            ,@RequestParam(name = "sort",defaultValue = "id") String sort
            ,@RequestParam(name = "order",defaultValue = "desc") String order
            ,Long productCategoryId
            ,Long productTypeId
            ,String cabCodes
            ,String skuName
            ,String brandName
            ,String typeName
            ,String name
            ,String skuCode
            ,String mainCabCode
    ) {
        Page<CellInventorySpaceVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        params.put("productCategoryId",productCategoryId);
        params.put("productTypeId",productTypeId);
        if (StringUtils.isNotBlank(cabCodes)){
            String [] cabCodeArray=cabCodes.split(",");
            params.put("cabCodes",cabCodeArray);
        }
        params.put("skuName",skuName);
        params.put("brandName",brandName);
        params.put("typeName",typeName);
        params.put("name",name);
        params.put("skuCode4app",skuCode);
        params.put("mainCabCode",mainCabCode);
        Page<CellInventorySpaceVO> list = cellInventorySpaceService.pageList4app(pg, params);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @GetMapping("detail/{id}")
    public JsonResult detail(@PathVariable("id") Long cellInventorySpaceId) {
        CellInventorySpaceVO cellInventorySpaceVO = cellInventorySpaceService.get4appById(cellInventorySpaceId);
        if (cellInventorySpaceVO == null) {
            return JsonResult.fail(localeMessage.getMessage("common.fail"));
        }
        return JsonResult.success(localeMessage.getMessage("common.success"), cellInventorySpaceVO);
    }

    @PostMapping()
    public JsonResult add(@Validated CellInventorySpaceForm cellInventorySpaceForm) {
        if (cellInventorySpaceService.add(cellInventorySpaceForm) > 0) {
            return JsonResult.success(localeMessage.getMessage("common.success"));
        }
        return JsonResult.fail(localeMessage.getMessage("common.fail"));
    }

}
